namespace SubhadraSolutions.Sharp.Logging.LogSubscribers.Database
{
    using SubhadraSolutions.Sharp.Logging.Contracts;
    using SubhadraSolutions.Sharp.Utils.Data;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;

    public class DatabaseLogLogger : AbstractLogSubscriber
    {
        #region Fields

        private IDbConnection _connection;

        #endregion Fields

        #region Properties

        public string ConnectionString
        {
            get;
            set;
        }

        public IDbStrategy DbStrategy
        {
            get;
            set;
        }

        public bool KeepConnectionOpen
        {
            get;
            set;
        }

        public ILoggerDataReader Reader
        {
            get;
            set;
        }

        public string TableName
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (_connection != null)
            {
                try
                {
                    _connection.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }

        protected override void initializeProtected()
        {
            Reader.Initialize();
            base.initializeProtected();
            if (KeepConnectionOpen)
            {
                _connection = DbStrategy.CreateConnection();
                _connection.ConnectionString = ConnectionString;
                _connection.Open();
            }
        }

        protected override void publishLogs(IEnumerable<LogStoreItem> e)
        {
            if (_connection != null)
            {
                doBulkCopy(_connection, e);
            }
            else
            {
                using (IDbConnection connection = DbStrategy.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    connection.Open();
                    doBulkCopy(connection, e);
                }
            }
        }

        private void doBulkCopy(IDbConnection connection, IEnumerable<LogStoreItem> e)
        {
            Reader.SetEnumerator(e.GetEnumerator(), false);
            DbStrategy.BulkCopier.DoBulkCopy(Reader, connection, TableName);
        }

        #endregion Methods
    }
}